package net.cyl.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;

import java.net.InetAddress;
import java.net.UnknownHostException;

@Configuration
@Slf4j
public class SnowFlakeWorkIdconfig {

    // 静态代码块，在类加载时执行
    static {
        try {
            // 获取本地主机地址
            InetAddress inetAddress = InetAddress.getLocalHost();
            // 获取本地主机地址的IP
            String hostAddressIp = inetAddress.getHostAddress();
            // 计算IP的哈希值，并取绝对值，然后对1024取模，得到workId
            String workId = Math.abs(hostAddressIp.hashCode()) % 1024+ "";
            // 设置系统属性workId
            System.setProperty("workId", workId);
            log.info("workId:{}",workId);
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
    }

//    public static void main(String[] args) {
//     InetAddress inetAddress = null;
//        try {
//            // 获取本地主机地址
//            inetAddress = InetAddress.getLocalHost();
//        } catch (UnknownHostException e) {
//            e.printStackTrace();
//        }
//        if (inetAddress != null) {
//            // 输出本地主机名
//            System.out.println(inetAddress.getHostName());
//        }
//        // 输出本地主机地址
//        System.out.println(inetAddress.getHostAddress());
//    }
}
